package com.aote.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.aote.constant.MessageConstant;
import com.aote.constant.RedisMessageConstant;
import com.aote.entity.Result;
import com.aote.pojo.Member;
import com.aote.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;
//处理会员相关操作
@RestController
@RequestMapping("/member")
public class MemberController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private MemberService memberService;
//手机号登录
    @RequestMapping("/login")
    public Result login(HttpServletResponse response, @RequestBody Map map){
        String telephone = (String) map.get("telephone");
//     从redis中获取保存的验证码
        String code = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        String  validateCode = (String) map.get("validateCode");
        if (validateCode != null && code != null &&code.equals(validateCode)){
//            验证码输入正确
//            判断当前用户是否为会员(查询会员表)
            Member member = memberService.findByTelephone(telephone);
            if (member==null){
//                不是会员,自动完成注册(将会员信息保存到会员表)
                Member newMember = new Member();
                newMember.setPhoneNumber(telephone);
                newMember.setRegTime(new Date());
                memberService.add(newMember);
            }
//           向浏览器写入cookie，内容为手机号
            Cookie cookie = new Cookie("member_telephone",telephone);
            cookie.setPath("/");
            cookie.setMaxAge(60*60*24*30);
            response.addCookie(cookie);
//            保存会员信息到redis中
            String json = JSON.toJSONString(member);
            jedisPool.getResource().setex(telephone,60*30,json);
            return new Result(true,MessageConstant.LOGIN_SUCCESS);
        }else {
//            验证码输入错误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }
}
